package cn.lili.modules.goods.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.distribution.entity.vos.HomeResult;
import cn.lili.modules.goods.entity.dos.*;
import cn.lili.modules.goods.entity.dto.GoodsHotPopularDTO;
import cn.lili.modules.goods.entity.dto.GoodsSearchParams;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.goods.entity.enums.GoodsTypeEnum;
import cn.lili.modules.goods.entity.vos.GoodsVO;
import cn.lili.modules.goods.entity.vos.yunxin.*;
import cn.lili.modules.goods.mapper.GoodsMapper;
import cn.lili.modules.goods.service.*;
import cn.lili.modules.goods.sku.GoodsSkuBuilder;
import cn.lili.modules.grab.alibaba.service.GoodsGrabService;
import cn.lili.modules.member.client.MemberEvaluationClient;
import cn.lili.modules.member.entity.dto.EvaluationQueryParams;
import cn.lili.modules.member.entity.enums.EvaluationGradeEnum;
import cn.lili.modules.operationcenter.client.OperationCenterClient;
import cn.lili.modules.operationcenter.entity.dos.OperationCenter;
import cn.lili.modules.operationcenter.entity.dto.OperationCenterSupplierDTO;
import cn.lili.modules.operationcenter.entity.vos.OperationCenterSupplierVo;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.promotion.client.BoxMhGoodsClient;
import cn.lili.modules.promotion.client.PromotionGoodsClient;
import cn.lili.modules.promotion.client.ReturnActivityGoodsClient;
import cn.lili.modules.promotion.entity.dos.BoxMhgoods;
import cn.lili.modules.promotion.entity.dos.BoxMhgoodsTag;
import cn.lili.modules.promotion.entity.dos.PromotionGoods;
import cn.lili.modules.promotion.entity.dos.ReturnActivityGoods;
import cn.lili.modules.promotion.entity.dto.search.PromotionGoodsSearchParams;
import cn.lili.modules.promotion.entity.enums.PromotionsStatusEnum;
import cn.lili.modules.promotion.entity.vos.BoxMhgoodsVO;
import cn.lili.modules.search.entity.dos.EsGoodsIndex;
import cn.lili.modules.search.entity.dto.EsGoodsSearchDTO;
import cn.lili.modules.store.client.FreightTemplateClient;
import cn.lili.modules.store.client.StoreClient;
import cn.lili.modules.store.entity.dos.FreightTemplate;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.supplier.entity.dto.SupplierGoodsOperationDTO;
import cn.lili.modules.system.client.DictionaryClient;
import cn.lili.modules.system.client.PackConfigClient;
import cn.lili.modules.system.client.SettingClient;
import cn.lili.modules.system.constants.DictConstant;
import cn.lili.modules.system.entity.dos.Dictionary;
import cn.lili.modules.system.entity.dos.PackConfig;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.mybatis.util.SceneHelp;
import cn.lili.routing.GoodsRoutingKey;
import cn.lili.util.HomeResultUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品业务层实现
 *
 * @author pikachu
 * @since 2020-02-23 15:18:56
 */
@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {


    @Resource
    private  MemberEvaluationClient memberEvaluationClient;

    @Resource
    private  FreightTemplateClient freightTemplateClient;

    @Resource
    private  GoodsSkuService goodsSkuService;

    @Resource
    private  Cache<GoodsVO> cache;

    @Resource
    private  StoreClient storeClient;

    @Resource
    private  RedisTemplate redisTemplate;

    @Resource
    private GoodsGalleryService goodsGalleryService;

    @Resource
    private  StoreGoodsLabelService storeGoodsLabelService;

    @Lazy
    @Resource
    private GoodsGrabService goodsGrabService;

    @Resource
    private  SettingClient settingClient;

    @Resource
    private  ApplicationEventPublisher applicationEventPublisher;
    @Resource
    private  AmqpExchangeProperties amqpExchangeProperties;

    @Resource
    private DictionaryClient dictionaryClient;

    @Resource
    private BoxMhGoodsClient boxMhGoodsClient;

    @Resource
    private PromotionGoodsClient promotionGoodsClient;

    @Resource
    private ReturnActivityGoodsClient returnActivityGoodsClient;

    @Resource
    private OperationCenterClient operationCenterClient;

    @Resource
    private GoodsDownRecordService goodsDownRecordService;

    @Resource
    private PackConfigClient packConfigClient;

    @Override
    public List<Goods> getByBrandIds(List<String> brandIds) {
        LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Goods::getBrandId, brandIds);
        return list(lambdaQueryWrapper);
    }

    @Override
    public void clearCache(String goodsId) {
        cache.remove(CachePrefix.GOODS.getPrefix() + goodsId);
    }

    /**
     * 更新商品参数
     *
     * @param goodsId 商品id
     * @param params  商品参数
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateGoodsParams(String goodsId, String params) {
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Goods::getId, goodsId);
        updateWrapper.set(Goods::getParams, params);
        this.update(updateWrapper);
    }

    @Override
    public final long getGoodsCountByCategory(String categoryId) {
        QueryWrapper<Goods> queryWrapper = Wrappers.query();
        queryWrapper.like("category_path", categoryId);
        queryWrapper.eq("delete_flag", false);
        return this.count(queryWrapper);
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateGoods(Goods goods) {
        log.info("goods----{}",JSONObject.toJSONString(goods));
        //修改商品
        this.updateById(goods);
        cache.remove(CachePrefix.GOODS.getPrefix() + goods.getId());
    }

    @Override
    public Page<GoodsVO> queryByParams(GoodsSearchParams goodsSearchParams) {
        QueryWrapper queryWrapper = goodsSearchParams.queryWrapper();
//        QueryInterface queryInterface = new QueryWrapperImpl.GoodsQueryWrapperImpl();
        if (SceneEnums.URBAN_SUBSTATION.equals(UserContext.getCurrentUser().getScene())) {
            List<Store> storeList = storeClient.getSupplierListByUrbanId(UserContext.getCurrentUser().getId());
            if (!storeList.isEmpty()) {
                List<String> extList = storeList.stream().map(Store::getId).collect(Collectors.toList());
                queryWrapper.in("store_id", extList);
            } else {
                queryWrapper.eq("store_id", "");
            }
        } else {
            SceneHelp.queryHandler(queryWrapper, true);
        }

        if (StringUtils.isNotEmpty(goodsSearchParams.getSelectName())) {
            List<StoreGoodsLabel> goodsLabels = storeGoodsLabelService.list(new LambdaQueryWrapper<StoreGoodsLabel>().eq(StoreGoodsLabel::getLabelName, goodsSearchParams.getSelectName()));
            if (CollectionUtil.isEmpty(goodsLabels)) {
                return new Page<GoodsVO>();
            }
            List<StoreGoodsLabel> addAllList = new ArrayList<>();
            for (StoreGoodsLabel goodsLabel : goodsLabels) {
                //如果是一级分类的数据，自动查询二级分类。一共二级分类
                if (goodsLabel.getLevel() == 0) {
                    List<StoreGoodsLabel> goodsLabelList = storeGoodsLabelService.list(new LambdaQueryWrapper<StoreGoodsLabel>().eq(StoreGoodsLabel::getParentId, goodsLabel.getId()));
                    addAllList.addAll(goodsLabelList);
                }
            }
            goodsLabels.addAll(addAllList);
            queryWrapper.in("store_category_path", goodsLabels.stream().map(StoreGoodsLabel::getId).collect(Collectors.toList()));
        }
        if (StringUtils.isNotEmpty(goodsSearchParams.getUrbanIdAndStoreId())) {
            String[] urbanSplit = goodsSearchParams.getUrbanIdAndStoreId().split(",");
            if (urbanSplit.length > 1) {
                //只查询店铺数据
                queryWrapper.in("store_id", urbanSplit[1]);
            } else {
                //只选择了城市店铺，需要查询城市站点下，所有的店铺
                List<Store> storeList = storeClient.getSupplierListByUrbanId(urbanSplit[0]);
                if (CollectionUtil.isEmpty(storeList)) {
                    queryWrapper.eq("id", -1);
                } else {
                    queryWrapper.in("store_id", storeList.stream().map(Store::getId).toList());
                }
            }
        }
        //礼包id
        if (StrUtil.isNotEmpty(goodsSearchParams.getPackId())) {
            queryWrapper.eq("pack_id", goodsSearchParams.getPackId());
        }

        if (StringUtils.isNotEmpty(goodsSearchParams.getPackName())) {
            List<PackConfig> packConfigList = packConfigClient.getPackConfigByField("pack_name", goodsSearchParams.getPackName());
            if (CollectionUtil.isEmpty(packConfigList)) {
                queryWrapper.eq("id", -1);
            } else {
                List<String> packIdList = packConfigList.stream().map(PackConfig::getId).map(String::valueOf).toList();
                queryWrapper.in("pack_id", packIdList);
            }
        }
        if (StringUtils.isNotEmpty(goodsSearchParams.getPackNo())) {
            List<PackConfig> packConfigList = packConfigClient.getPackConfigByField("pack_no", goodsSearchParams.getPackNo());
            if (CollectionUtil.isEmpty(packConfigList)) {
                queryWrapper.eq("id", -1);
            } else {
                List<String> packIdList = packConfigList.stream().map(PackConfig::getId).map(String::valueOf).toList();
                queryWrapper.in("pack_id", packIdList);
            }
        }
        queryWrapper.eq("delete_flag",false);
        Page<Goods> page = baseMapper.pageVo(PageUtil.initPage(goodsSearchParams), queryWrapper, goodsSearchParams.getGoodsName());
        if (CollUtil.isNotEmpty(page.getRecords())) {
            //stream 从 List<Goods> 里获取 packId属性不为空 的所有不重复的packId值 , 返回list
                List<String> packIdList = page.getRecords().stream().filter(e -> StringUtils.isNotEmpty(e.getPackId())).map(Goods::getPackId).map(String::valueOf).toList();
                if (CollectionUtil.isNotEmpty(packIdList)) {
                    List<PackConfig> packConfigList = packConfigClient.getPackConfigByPackIds(packIdList);
                    if (CollectionUtil.isNotEmpty(packConfigList)) {
                        return this.pageConversion(page, packConfigList);
                    }
                }
        }
        return this.pageConversion(page, null);
    }

    private Page<GoodsVO> pageConversion(Page<Goods> page, List<PackConfig> packConfigList) {
        if (CollectionUtil.isEmpty(page.getRecords())) {
            return new Page<>();
        }
        Page<GoodsVO> resultPage = new Page<>();
        BeanUtils.copyProperties(page, resultPage);
//        List<GoodsVO> voList = CglibUtil.copyList(page.getRecords(), GoodsVO::new);
        List<GoodsVO> voList = BeanUtil.copyToList(page.getRecords(), GoodsVO.class);
        resultPage.setRecords(voList);

        //字典转换
        List<Dictionary> tagNameList = dictionaryClient.getListByCode(DictConstant.TAG_NAME);
        List<Dictionary> publishList = dictionaryClient.getListByCode(DictConstant.PUBLISH_TYPE_NO);
        String mhIds = voList.stream().map(GoodsVO::getMhId).collect(Collectors.joining(","));
        List<BoxMhgoods> mhgoodsList = boxMhGoodsClient.getByIds(mhIds);

        resultPage.getRecords().forEach(f -> f.setIsNew(false));

        List<Integer> thirdPartyIdList = resultPage.getRecords().stream().filter(f -> StringUtils.isNotEmpty(f.getThirdPartyPlatformId()) && f.getThirdPartyPlatformType() != null && f.getThirdPartyPlatformType().equals(1)).map(GoodsVO::getThirdPartyPlatformId).map(Integer::valueOf).toList();
        if (CollectionUtil.isNotEmpty(thirdPartyIdList)) {
            List<JSONObject> platformGoodsDetail = this.getPlatformGoodsDetail(thirdPartyIdList);
            if (CollectionUtil.isNotEmpty(platformGoodsDetail)) {
                for (JSONObject jsonObject : platformGoodsDetail) {
                    ProductDetailVO productDetailVO = JSONObject.parseObject(String.valueOf(jsonObject), ProductDetailVO.class);
                    for (GoodsVO goodsVO: resultPage.getRecords()) {
                        if (StringUtils.isNotEmpty(goodsVO.getThirdPartyPlatformId()) && goodsVO.getThirdPartyPlatformId().equals(String.valueOf(productDetailVO.getId()))) {
                            //0下架，1上架
                            goodsVO.setOffAndOnCondition(productDetailVO.getIs_display() != null && productDetailVO.getIs_display().equals(1) ? "上架":"下架");
                        }
                    }
                }
            }
        }

        for (GoodsVO goodsVO: resultPage.getRecords()) {
            Date date = DateUtil.offsetWeek(new Date(), -1).toJdkDate();
            if (goodsVO.getCreateTime() != null && goodsVO.getCreateTime().getTime() > date.getTime()) {
                goodsVO.setIsNew(true);
            }
            if (CollectionUtil.isNotEmpty(tagNameList)) {
                for (Dictionary dictionary : tagNameList) {
                    if (String.valueOf(goodsVO.getGoodsTag()).equals(dictionary.getValue())) {
                        goodsVO.setGoodsTagName(dictionary.getValueName());
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(publishList)) {
                for (Dictionary dictionary : publishList) {
                    if (String.valueOf(goodsVO.getPublishType()).equals(dictionary.getValue())) {
                        goodsVO.setPublishTypeName(dictionary.getValueName());
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(mhgoodsList)) {
                for (BoxMhgoods boxMhgoods : mhgoodsList) {
                    if (boxMhgoods.getId().equals(goodsVO.getMhId())) {
                        goodsVO.setMhName(boxMhgoods.getMhGoodsName());
                    }
                }
            }
            //赋值礼包名称
            if (CollUtil.isNotEmpty(packConfigList)) {
                for (PackConfig packConfig : packConfigList) {
                    if (StringUtils.isNotEmpty(goodsVO.getPackId()) && goodsVO.getPackId().equals(packConfig.getId())) {
                        goodsVO.setPackName(packConfig.getPackName());
                    }
                }
            }
        }

        return resultPage;
    }


    @Override
    public Page<Goods> queryGoodsByParams(GoodsSearchParams goodsSearchParams) {
        log.debug("========goodsSearchParams===>"+ JSON.toJSONString(goodsSearchParams));
        QueryWrapper queryWrapper = goodsSearchParams.queryWrapper();
        return this.page(PageUtil.initPage(goodsSearchParams), queryWrapper);
    }


    /**
     * 商品查询
     *
     * @param goodsSearchParams 查询参数
     * @return 商品信息
     */
    @Override
    public List<Goods> queryListByParams(GoodsSearchParams goodsSearchParams) {
        return this.list(goodsSearchParams.queryWrapper());
    }

    @Override
    public List<String> queryListIdByParams(GoodsSearchParams goodsSearchParams) {
        return this.baseMapper.getGoodsSkuIdByGoodsId(goodsSearchParams.queryWrapper());
    }

    @Override
    public List<String> queryListStoreIdByParams(GoodsSearchParams goodsSearchParams) {
        return this.baseMapper.getGoodsSkuStoreIdByGoodsId(goodsSearchParams.queryWrapper());
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public Boolean freight(List<String> goodsIds, String templateId) {
        //获取当前用户
        String storeId = UserContext.getCurrentUser().getExtendId();
        //获取运费模板
        FreightTemplate freightTemplate = freightTemplateClient.getFreightTemplate(templateId);
        if (freightTemplate == null) {
            throw new ServiceException(ResultCode.FREIGHT_TEMPLATE_NOT_EXIST);
        }
        //判断运费模板是否属于当前店铺
        if (!freightTemplate.getStoreId().equals(storeId)) {
            throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
        }
        LambdaUpdateWrapper<Goods> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.set(Goods::getTemplateId, templateId);
        lambdaUpdateWrapper.eq(Goods::getStoreId, storeId);
        lambdaUpdateWrapper.in(Goods::getId, goodsIds);
        //删除商品缓存
        cache.multiDel(goodsIds.stream().map(id -> CachePrefix.GOODS.getPrefix() + id).collect(Collectors.toList()));
        return this.update(lambdaUpdateWrapper);
    }

    @Override
    public void updateStock(String goodsId, Integer quantity) {
        LambdaUpdateWrapper<Goods> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.set(Goods::getQuantity, quantity);
        lambdaUpdateWrapper.eq(Goods::getId, goodsId);
        cache.remove(CachePrefix.GOODS.getPrefix() + goodsId);
        this.update(lambdaUpdateWrapper);
    }

    @Override
    @Transactional
    public void updateStock(List<GoodsSku> goodsSkus) {
        // 根据商品id分组
        Map<String, List<GoodsSku>> groupByGoodId = goodsSkus.stream().collect(Collectors.groupingBy(GoodsSku::getGoodsId));
        //统计每个商品的库存
        for (Map.Entry<String, List<GoodsSku>> entry : groupByGoodId.entrySet()) {
            // 商品库存同步
            this.syncStock(entry.getKey());
        }
    }

    @Override
    public void syncStock(String goodsId) {
        Goods goods = this.getById(goodsId);
        // 如果商品不存在，则不同步库存
        if (goods == null) {
            return;
        }
        Integer stock = goodsSkuService.getGoodsStock(goodsId);
        // 如果是供应商商品同步库存，则将所有代理该商品的供应商商品库存同步
        if (goods.getScene().equals(SceneEnums.SUPPLIER.name())) {
            // 设置商品库存总数
            this.updateStockBySupplierGoodsID(goodsId, stock);
        }
        this.updateStock(goodsId, stock);
    }

    @Override
    public void updateGoodsCommentNum(String goodsId) {

        //获取商品信息
        Goods goods = this.getById(goodsId);
        //修改商品评价数量
        goods.setCommentNum(goods.getCommentNum() + 1);

        //修改商品好评率
        EvaluationQueryParams queryParams = new EvaluationQueryParams();
        queryParams.setGoodsId(goodsId);
        queryParams.setGrade(EvaluationGradeEnum.GOOD.name());

        //好评数量
        long highPraiseNum = memberEvaluationClient.getEvaluationCount(queryParams);
        //好评率
        double grade = NumberUtil.mul(NumberUtil.div(highPraiseNum, goods.getCommentNum().doubleValue(), 2), 100);
        goods.setGrade(grade);
        this.updateById(goods);
    }

    /**
     * 更新商品的购买数量
     *
     * @param goodsId  商品ID
     * @param buyCount 购买数量
     */
    @Override
    public void updateGoodsBuyCount(String goodsId, int buyCount) {
        this.update(new LambdaUpdateWrapper<Goods>()
                .eq(Goods::getId, goodsId)
                .set(Goods::getBuyCount, buyCount));
    }

    @Override
    public long countStoreGoodsNum(String storeId) {
        return this.count(
                new LambdaQueryWrapper<Goods>()
                        .eq(Goods::getStoreId, storeId)
                        .eq(Goods::getDeleteFlag, Boolean.FALSE)
                        .eq(Goods::getAuthFlag, GoodsAuthEnum.PASS.name())
                        .eq(Goods::getMarketEnable, GoodsMarketEnum.UPPER.name()));
    }


    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void addGoodsCommentNum(Integer commentNum, String goodsId) {
        this.baseMapper.addGoodsCommentNum(commentNum, goodsId);
    }

    @Override
    public Goods getGoodsByParams(GoodsSearchParams goodsSearchParams) {
        return this.getOne(goodsSearchParams.queryWrapper(), false);
    }

    @Override
    public long countGoodsNum(GoodsSearchParams goodsSearchParams) {
        return this.count(goodsSearchParams.queryWrapper());
    }

    @Override
    public void updateGoodsIntro(Goods goods) {
        LambdaUpdateWrapper<Goods> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.set(Goods::getIntro, goods.getIntro());
        lambdaUpdateWrapper.set(Goods::getOriginal, goods.getOriginal());
        lambdaUpdateWrapper.set(Goods::getSmall, goods.getSmall());
        lambdaUpdateWrapper.set(Goods::getThumbnail, goods.getThumbnail());
        lambdaUpdateWrapper.eq(Goods::getId, goods.getId());
        this.update(lambdaUpdateWrapper);
    }

    @Override
    public ResultMessage<Object> sycn() {
        List<Goods> goodsList = super.list(new LambdaQueryWrapper<Goods>()
                .isNull(Goods::getDefaultSkuGreenScore).or().isNull(Goods::getPrice)
                .select(Goods::getId));
        if (CollectionUtil.isEmpty(goodsList)) {
            return null;
        }
        List<GoodsSku> goodsSkus = goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>()
                .in(GoodsSku::getGoodsId, goodsList.stream().map(Goods::getId).collect(Collectors.toList()))
                .select(GoodsSku::getGoodsId, GoodsSku::getPrice, GoodsSku::getGreenScore));
        Map<String, List<GoodsSku>> listMap = goodsSkus.stream().filter(f -> StringUtils.isNotEmpty(f.getGoodsId())).collect(Collectors.groupingBy(GoodsSku::getGoodsId));

        for (Map.Entry<String, List<GoodsSku>> stringListEntry : listMap.entrySet()) {
            for (Goods goods : goodsList) {
                Double greenScore = 0D;
                Double price = Double.MAX_VALUE;
                if (CollectionUtil.isNotEmpty(stringListEntry.getValue()) && goods.getId().equals(stringListEntry.getKey())) {
                    for (GoodsSku goodsSku : stringListEntry.getValue()) {
                        if (price > goodsSku.getPrice()) {
                            price = goodsSku.getPrice();
                            greenScore = goodsSku.getGreenScore();
                        }
                    }
                    goods.setDefaultSkuGreenScore(greenScore != null ? BigDecimal.valueOf(greenScore) : BigDecimal.valueOf(0));
                    goods.setPrice(price);
                    super.updateById(goods);
                }
            }
        }
        return null;
    }

    @Override
    public List<GoodsVO> geBlindbox() {
        List<GoodsVO> resultList = new ArrayList<>();

        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getDeleteFlag, Boolean.FALSE);
        queryWrapper.eq(Goods::getAuthFlag, GoodsAuthEnum.PASS.name());
        queryWrapper.eq(Goods::getMarketEnable, GoodsMarketEnum.UPPER.name());
        queryWrapper.eq(Goods::getGoodsType, GoodsTypeEnum.BLINDBOX_GOODS.name());
        queryWrapper.orderByDesc(Goods::getCreateTime);
        List<Goods> goodsList = this.list(queryWrapper);
        if (goodsList != null && goodsList.size() > 0) {
            for (Goods goods : goodsList) {
                GoodsVO goodsVO = new GoodsVO();
                //商品相册赋值
                List<String> images = new ArrayList<>();
                List<GoodsGallery> galleryList = goodsGalleryService.goodsGalleryList(goods.getId());
                for (GoodsGallery goodsGallery : galleryList) {
                    images.add(goodsGallery.getOriginal());
                }
                //赋值VO
                BeanUtils.copyProperties(goods, goodsVO);
                goodsVO.setGoodsGalleryList(images);
                resultList.add(goodsVO);
            }

        }
        return resultList;
    }

    @Override
    public List<String> getGoodsIdListByGreenFlag(Integer isGreenGoods) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id").lambda().eq(Goods::getIsGreenGoods, isGreenGoods);
        List<Goods> list = this.baseMapper.selectList(queryWrapper);
        if (null != list && !list.isEmpty()) {
            return list.stream().map(item -> item.getId()).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 根据供应商商品ID更新库存
     *
     * @param supplierGoodsId 商品ID
     * @param quantity        库存
     */
    private void updateStockBySupplierGoodsID(String supplierGoodsId, Integer quantity) {
        LambdaUpdateWrapper<Goods> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.set(Goods::getQuantity, quantity);
        lambdaUpdateWrapper.eq(Goods::getSupplierGoodsId, supplierGoodsId);
        this.update(lambdaUpdateWrapper);
    }

    String str = "https://supply.yibangjiu.com/supplyapi";

    public String getToken() {
        Object token = redisTemplate.boundValueOps("yunxin_token").get();
        if (token != null) {
            return (String) token;
        }
        String tokenUrl = str + "/app/application/getToken";
        Map<String, Object> params = new HashMap<>();
        params.put("app_key", "application4");
        params.put("app_secret", "a7c5dbc8aaa6a67bc2a73b1d71faeb91");
        HttpRequest post1 = HttpUtil.createPost(tokenUrl).body(JSONObject.toJSONString(params));
        String body = post1.execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.getInteger("code") != 0) {
            throw new ServiceException("token获取失败");
        }
        redisTemplate.boundValueOps("yunxin_token").set(jsonObject.getJSONObject("data").getString("token"));
        redisTemplate.expire("yunxin_token", 30, TimeUnit.MINUTES);
        return jsonObject.getJSONObject("data").getString("token");
    }


    public List<JSONObject> getPlatformGoodsList(GoodsSearchParams goodsSearchParams) {
        String token = this.getToken();
        String goodsListUrl = "/app/product/storage/cursorList";

        try {
            Map<String, Object> params = new HashMap<>();
            params.put("pageSize", goodsSearchParams.getPageSize());
            params.put("cursor", goodsSearchParams.getCursor());
            //不将下架的商品，查询出来
//            params.put("is_import", 2);
            params.put("is_display", 1);
            if (StringUtils.isNotEmpty(goodsSearchParams.getGoodsName())) {
                params.put("title", goodsSearchParams.getGoodsName());
            }
            if (StringUtils.isNotEmpty(goodsSearchParams.getSupplierName())) {
                params.put("supplier_name", goodsSearchParams.getSupplierName());
            }
            log.info("cursorList 请求参数：{}", JSONObject.toJSONString(params));
            HttpRequest post1 = HttpUtil.createPost(str + goodsListUrl).header("x-token", token).body(JSONObject.toJSONString(params));
            String body = post1.execute().body();
            JSONObject jsonObject = JSONObject.parseObject(body);

            if (jsonObject.getInteger("code") != 0) {
                throw new ServiceException("获取列表失败");
            }
            if (jsonObject.get("data") == null) {
                return new ArrayList<>();
            }
            List<JSONObject> productVOList = (List<JSONObject>) JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("data"))).get("list");
            log.info("cursorList 返回数据：{}", JSONObject.toJSONString(productVOList));
            return productVOList;
        } catch (Exception e) {
            log.error("获取列表异常 :  " + e.getMessage());
            throw new ServiceException("获取列表异常");
        }
    }

    public List<JSONObject> getPlatformGoodsList2(GoodsSearchParams goodsSearchParams) {
        String token = this.getToken();
        String goodsListUrl = "/app/product/storage/list";

        try {
            Map<String, Object> params = new HashMap<>();
            params.put("pageSize", goodsSearchParams.getPageSize());
            params.put("cursor", goodsSearchParams.getCursor());
            //不将下架的商品，查询出来
//            params.put("is_import", 2);
            params.put("is_display", 1);
            if (StringUtils.isNotEmpty(goodsSearchParams.getGoodsName())) {
                params.put("title", goodsSearchParams.getGoodsName());
            }
            if (StringUtils.isNotEmpty(goodsSearchParams.getSupplierName())) {
                params.put("supplier_name", goodsSearchParams.getSupplierName());
            }
            log.info("cursorList 请求参数：{}", JSONObject.toJSONString(params));
            HttpRequest post1 = HttpUtil.createPost(str + goodsListUrl).header("x-token", token).body(JSONObject.toJSONString(params));
            String body = post1.execute().body();
            JSONObject jsonObject = JSONObject.parseObject(body);

            if (jsonObject.getInteger("code") != 0) {
                throw new ServiceException("获取列表失败");
            }
            if (jsonObject.get("data") == null) {
                return new ArrayList<>();
            }
            List<JSONObject> productVOList = (List<JSONObject>) JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("data"))).get("list");
            log.info("cursorList 返回数据：{}", JSONObject.toJSONString(productVOList));
            return productVOList;
        } catch (Exception e) {
            log.error("获取列表异常 :  " + e.getMessage());
            throw new ServiceException("获取列表异常");
        }
    }

    /**
     * 商品列表转换
     *
     * @param productVOList 第三方产品
     * @return 平台商品
     */
    public List<Goods> goodsConversion(List<JSONObject> productVOList) {
        if (CollectionUtil.isEmpty(productVOList)) {
            return new ArrayList<>();
        }
        List<Goods> goodsList = new ArrayList<>();
        for (JSONObject product : productVOList) {
            ProductVO productVO = JSONObject.parseObject(String.valueOf(product), ProductVO.class);
            if (Integer.valueOf(0).equals(productVO.getIs_display())) {
                continue;
            }
            Goods goods = new Goods();
            goods.setDeleteFlag(true);
            goods.setBuyCount(0);
            goods.setCategoryPath(productVO.getCategory_1_id() + "," + productVO.getCategory_2_id() + "," + productVO.getCategory_3_id());
            goods.setGoodsName("Y-" + productVO.getTitle());
            goods.setIntro(null);
            goods.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
            goods.setMarketEnable(GoodsMarketEnum.DOWN.name());
            goods.setMobileIntro(null);
            goods.setOriginal(productVO.getImage_url());
            goods.setPrice(productVO.getCost_price() != null ? BigDecimal.valueOf(productVO.getCost_price() * 1.05).divide(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_UP).doubleValue() : Double.MAX_VALUE);
            goods.setQuantity(productVO.getStock());
            goods.setRecommend(true);
            goods.setSalesModel("RETAIL");
            goods.setSelfOperated(true);
            goods.setSmall(productVO.getImage_url());
            goods.setTemplateId("0");
            goods.setThumbnail(productVO.getImage_url());
            goods.setBig(productVO.getImage_url());
            goods.setGoodsType("PHYSICAL_GOODS");
            goods.setSupplierId(String.valueOf(productVO.getSupplier_id()));
            goods.setIsGreenGoods(false);

            List<Integer> list = new ArrayList<>();
            list.add(productVO.getId());
            List<JSONObject> platformGoodsDetail = this.getPlatformGoodsDetail(list);
            StringBuffer buffer = new StringBuffer();
            for (JSONObject jsonObject : platformGoodsDetail) {
                ProductDetailVO productDetailVO = JSONObject.parseObject(String.valueOf(jsonObject), ProductDetailVO.class);
                buffer.append(productDetailVO.getDetail_images());
            }

            goods.setIntro(buffer.toString());
            goods.setMobileIntro(buffer.toString());
            goods.setScene("STORE");
            goods.setExtendId("1713890839052210178");
            goods.setStoreId("1713890839052210178");
            goods.setStoreName("供应");
            goods.setGid(productVO.getId());
            goods.setThirdPartyPlatformId(productVO.getId()+"");
            goods.setThirdPartyPlatformType(1);
            goods.setStoreCategoryPath(productVO.getCategory_2_id() + "");
            goods.setGoodsUnit("件");

            goodsList.add(goods);
        }
        return goodsList;
    }

    /**
     * sku转换
     *
     * @return
     */
    public Map<String, List> goodsSkusConversion(List<JSONObject> productDetailVOList, List<Goods> goodsList) {
        Map<String, List> map = new HashMap<>();

        List<GoodsSku> goodsSkusList = new ArrayList<>();
        List<GoodsGallery> goodsGalleryList = new ArrayList<>();
        if (CollectionUtil.isEmpty(productDetailVOList)) {
            map.put("goods_sku", goodsSkusList);
            map.put("img", goodsGalleryList);
            log.info("productDetailVOList  null");
            return map;
        }
        for (JSONObject product : productDetailVOList) {
//           ProductDetailVO productDetailVO =  (ProductDetailVO) product.get;
            ProductDetailVO productDetailVO = JSONObject.parseObject(String.valueOf(product), ProductDetailVO.class);
            for (Goods goods : goodsList) {
                if (!goods.getThirdPartyPlatformId().equals(String.valueOf(productDetailVO.getId()))) {
                    continue;
                }
                for (GalleryVO galleryVO : productDetailVO.getGallery()) {
                    GoodsGallery goodsGallery = new GoodsGallery();
                    goodsGallery.setGoodsId(goods.getId());
                    goodsGallery.setIsDefault(0);
                    goodsGallery.setOriginal(galleryVO.getSrc());
                    goodsGallery.setSmall(galleryVO.getSrc());
                    goodsGallery.setThumbnail(galleryVO.getSrc());
                    goodsGalleryList.add(goodsGallery);
                }

                for (SkusVO skus : productDetailVO.getSkus()) {
                    log.info("skus == {}", JSONObject.toJSONString(skus));
                    GoodsSku goodsSku = new GoodsSku();
                    goodsSku.setDeleteFlag(true);
                    goodsSku.setIs_display(productDetailVO.getIs_display());
                    goodsSku.setBuyCount(0);
                    StringBuffer stringBuffer = new StringBuffer();
                    if (productDetailVO.getCategory1_id() != null) {
                        stringBuffer.append(productDetailVO.getCategory1_id()).append(",");
                    }
                    if (productDetailVO.getCategory2_id() != null) {
                        stringBuffer.append(productDetailVO.getCategory2_id()).append(",");
                    }
                    if (productDetailVO.getCategory3_id() != null) {
                        stringBuffer.append(productDetailVO.getCategory3_id()).append(",");
                    }
                    if (stringBuffer.length() > 0) {
                        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                    }
                    goodsSku.setCategoryPath(stringBuffer.toString());
                    goodsSku.setCommentNum(0);
                    goodsSku.setGoodsId(goods.getId());
                    goodsSku.setGoodsName("Y-" + productDetailVO.getTitle());
                    goodsSku.setStoreId("1713890839052210178");
                    goodsSku.setStoreName("供应");
                    goodsSku.setSn(productDetailVO.getSn());
                    String img = StringUtils.isNotEmpty(skus.getImage_url()) ? skus.getImage_url() : productDetailVO.getImage_url();
                    StringBuilder specs = new StringBuilder("{\"images\":[{\"url\":\"" + img + "\"}]");
                    //TODO 此处可能出现
                    for (SpecsVO option : skus.getOptions()) {
                        log.info("option == {}", JSONObject.toJSONString(option));
                        if (StringUtils.isEmpty(option.getSpec_item_name())) {
                            continue;
                        }
//                        StringUtils.isEmpty(option.getSpec_name()) ||
                        specs.append(",").append("\"").append(StringUtils.isEmpty(option.getSpec_name()) ? "规格" : option.getSpec_name()).append("\"").append(":").append("\"").append(option.getSpec_item_name()).append("\"");
                        goodsSku.setSimpleSpecs(option.getSpec_item_name());
                    }
                    goodsSku.setSpecs(specs.toString() + "}");
                    goodsSku.setGoodsType("PHYSICAL_GOODS");
                    goodsSku.setIsGreenGoods(false);
                    goodsSku.setQuantity(productDetailVO.getStock());
                    goodsSku.setWeight(Double.valueOf(skus.getWeight()));
                    goodsSku.setCost(StringUtils.isNotEmpty(skus.getCost_price()) ? BigDecimal.valueOf(Double.parseDouble(skus.getCost_price())).divide(BigDecimal.valueOf(100)).doubleValue() : Double.MAX_VALUE);
                    goodsSku.setPrice(StringUtils.isNotEmpty(skus.getCost_price()) ? BigDecimal.valueOf(Double.parseDouble(skus.getCost_price()) * 1.05).divide(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_UP).doubleValue() : Double.MAX_VALUE);
                    goodsSku.setGreenScore(goodsSku.getCost() * 0.05);
                    goodsSku.setIsProxyGoods(true);
                    goodsSku.setScene("STORE");
                    goodsSku.setFreightTemplateId("0");
                    goodsSku.setGrade(100D);
//                    goodsSku.setMarketEnable("UPPER");
//                    goodsSku.setAuthFlag("PASS");
                    goodsSku.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
                    goodsSku.setMarketEnable(GoodsMarketEnum.DOWN.name());
                    goodsSku.setRecommend(true);
                    goodsSku.setSalesModel("RETAIL");
                    goodsSku.setSelfOperated(false);
                    goodsSku.setTemplateId("0");
                    goodsSku.setOriginal(img);
                    goodsSku.setThumbnail(img);
                    goodsSku.setBig(img);
                    goodsSku.setSmall(img);
                    goodsSku.setIsProxyGoods(false);
                    goodsSku.setSupportProxy(false);
                    goodsSku.setSupportPurchase(false);
                    goodsSku.setThirdPartyPlatformId(skus.getId());
                    goodsSku.setThirdPartyPlatformType(1);
                    goodsSku.setExtendId("1713890839052210178");
                    goodsSku.setStoreCategoryPath(stringBuffer.toString());
                    goodsSku.setGoodsUnit("件");
                    goodsSku.setIntro(goods.getIntro());
                    goodsSku.setMobileIntro(goods.getMobileIntro());
                    goodsSku.setMaxfNumber(0D);


                    goodsSkusList.add(goodsSku);
                }
            }
        }
        map.put("goods_sku", goodsSkusList);
        map.put("img", goodsGalleryList);
        return map;
    }

    /**
     * 获取商品详情
     *
     * @return
     */
    public List<JSONObject> getPlatformGoodsDetail(List<Integer> goodsIds) {
        String token = this.getToken();
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("ids", goodsIds);
            HttpRequest httpRequest = HttpUtil.createPost(str + "/app/product/storage/detailList").header("x-token", token).body(JSONObject.toJSONString(params));
            String body = httpRequest.execute().body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject.getInteger("code") != 0) {
                throw new ServiceException("获取详情失败");
            }
            List<JSONObject> productDetailVOList = (List<JSONObject>) JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("data"))).get("list");
            log.info("productDetailVOList == {}", JSONObject.toJSONString(productDetailVOList));
            return productDetailVOList;
        } catch (Exception e) {
            log.error("获取详情异常 :  " + e.getMessage());
            throw new ServiceException("获取详情异常");
        }
    }

    /**
     * 获取所有分类，初始化到店铺分类中
     *
     * @return
     */
    public ResultMessage<Object> getCategoryTree() {
        try {
            String token = this.getToken();
            HttpRequest httpRequest = HttpUtil.createGet(str + "/app/category/tree").header("x-token", token);
            String body = httpRequest.execute().body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject.getInteger("code") != 0) {
                throw new ServiceException("获取分类异常");
            }
            jsonObject.get("data");
            List<StoreGoodsLabel> storeGoodsLabels = this.goodsLabelList(body);
            storeGoodsLabelService.saveBatch(storeGoodsLabels);
            return ResultUtil.success();
        } catch (Exception e) {
            log.error("获取商品分类异常" + e.getMessage());
            return ResultUtil.error(500, "获取商品分类异常");
        }
    }

    public List<StoreGoodsLabel> goodsLabelList(String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        List<StoreGoodsLabel> storeGoodsLabels = new ArrayList<>();

        if (jsonObject.getInteger("code") == 0) {
            JSONObject dataJson = jsonObject.getJSONObject("data");
            JSONArray categories = dataJson.getJSONArray("categories");
            for (Object category : categories) {
                if (category == null) {
                    continue;
                }
                JSONObject object = (JSONObject) category;
                StoreGoodsLabel storeGoodsLabel = new StoreGoodsLabel();
                storeGoodsLabel.setStoreId("1713890839052210178");
                storeGoodsLabel.setLevel(0);
                storeGoodsLabel.setId(object.getString("id"));
                storeGoodsLabel.setLabelName(object.getString("name"));
                storeGoodsLabel.setDeleteFlag(true);
                storeGoodsLabel.setParentId("0");
                storeGoodsLabel.setSortOrder(BigDecimal.valueOf(0));
                storeGoodsLabels.add(storeGoodsLabel);
                if (object.get("children") != null) {
                    JSONArray children = object.getJSONArray("children");
                    for (Object child : children) {
                        if (child == null) {
                            continue;
                        }
                        JSONObject childJson = (JSONObject) child;
                        StoreGoodsLabel storeGoodsLabel2 = new StoreGoodsLabel();
                        storeGoodsLabel2.setStoreId("1713890839362588672");
                        storeGoodsLabel2.setLevel(1);
                        storeGoodsLabel2.setId(childJson.getString("id"));
                        storeGoodsLabel2.setLabelName(childJson.getString("name"));
                        storeGoodsLabel2.setDeleteFlag(true);
                        storeGoodsLabel2.setParentId(object.getString("id"));
                        storeGoodsLabel2.setSortOrder(BigDecimal.valueOf(0));
                        storeGoodsLabels.add(storeGoodsLabel2);

                        JSONArray children2 = childJson.getJSONArray("children");
                        for (Object child2 : children2) {
                            if (child2 == null) {
                                continue;
                            }
                            JSONObject child2Json = (JSONObject) child2;
                            StoreGoodsLabel storeGoodsLabel3 = new StoreGoodsLabel();
                            storeGoodsLabel3.setStoreId("1713890839362588672");
                            storeGoodsLabel3.setLevel(2);
                            storeGoodsLabel3.setId(child2Json.getString("id"));
                            storeGoodsLabel3.setLabelName(child2Json.getString("name"));
                            storeGoodsLabel3.setDeleteFlag(true);
                            storeGoodsLabel3.setParentId(childJson.getString("id"));
                            storeGoodsLabel3.setSortOrder(BigDecimal.valueOf(0));
                            storeGoodsLabels.add(storeGoodsLabel3);
                        }
                    }
                }
            }
        }
        return storeGoodsLabels;
    }


    /**
     * 把第三方平台数据导入到，店铺
     *
     * @return
     */
    public Boolean addGoods(GoodsSearchParams goodsSearchParams) {
        //获取所有商品详情的sku，然后导入到sku中。
        List<JSONObject> platformGoodsList = getPlatformGoodsList(goodsSearchParams);
        log.info("platformGoodsList 1 1 = {}", JSONObject.toJSONString(platformGoodsList));
        List<Goods> goodsList = this.goodsConversion(platformGoodsList);
        log.info("goodsList 1 1 = {}", JSONObject.toJSONString(goodsList));
        super.saveBatch(goodsList);

        List<Integer> goodsIdList = goodsList.stream().map(Goods::getGid).collect(Collectors.toList());
        List<JSONObject> platformGoodsDetail = getPlatformGoodsDetail(goodsIdList);
        log.info("platformGoodsDetail 1 1 = {}", JSONObject.toJSONString(platformGoodsDetail));
        Map<String, List> map = this.goodsSkusConversion(platformGoodsDetail, goodsList);
        log.info("map 1 1 = {}", JSONObject.toJSONString(map));
        boolean b = goodsSkuService.saveBatch(map.get("goods_sku"));

        boolean b1 = goodsGalleryService.saveBatch(map.get("img"));
        List<GoodsSku> goodsSku = map.get("goods_sku");

        this.addStorage(goodsIdList.stream().collect(Collectors.toList()));
        this.addStorage(goodsSku.stream().map(GoodsSku::getThirdPartyPlatformId).map(Integer::valueOf).collect(Collectors.toList()));
        return !goodsList.isEmpty();
    }

    @Override
    public Page<EsGoodsIndex> esGoodsIndicesNull(Page<EsGoodsIndex> esGoodsIndices) {
        try {
            //如果缺少图片，则从数据库查询
            if (esGoodsIndices != null && esGoodsIndices.getRecords() != null && !esGoodsIndices.getRecords().isEmpty()) {
                List<EsGoodsIndex> list = esGoodsIndices.getRecords().stream().map(e -> {
                    if (StringUtils.isEmpty(e.getThumbnail()) || !e.getThumbnail().startsWith("http") || !e.getThumbnail().startsWith("https")) {
                        //查询数据库图片
                        log.info("如果缺少图片，则从数据库查询--" + JSONObject.toJSONString(e));
                        Goods byId = this.getById(e.getGoodsId());
                        e.setThumbnail(byId.getThumbnail());
                    }

                    //图片处理
                    if(StringUtils.isNotEmpty(e.getThumbnail())){
                        e.setThumbnail(e.getThumbnail().split("\\?")[0]);
                    }
                    return e;
                }).toList();
                esGoodsIndices.setRecords(list);
            }
        } catch (Exception e) {
            log.info("如果缺少图片，则从数据库查询报错--" + JSONObject.toJSONString(e));
        }
        return esGoodsIndices;
    }

    @Override
    public Page<EsGoodsIndex> esGoodsIndicesDown(Page<EsGoodsIndex> esGoodsIndices) {
        if (esGoodsIndices != null && esGoodsIndices.getRecords() != null && !esGoodsIndices.getRecords().isEmpty()) {
            List<EsGoodsIndex> list = esGoodsIndices.getRecords().stream().filter(e -> {
                //展示 价格=价格+绿色积分
//              e.setPrice(e.getPrice() + (e.getGreenScore() != null ? e.getGreenScore() : 0.0));
                GoodsSku sku = goodsSkuService.getById(e.getId());
                if (sku != null && sku.getThirdPartyPlatformType() != null && sku.getThirdPartyPlatformType() == 4) {
                    e.setIsFree(Boolean.TRUE);
                }Goods goods = this.getById(e.getGoodsId());return goods != null && goods.getAuthFlag().equals(GoodsAuthEnum.PASS.name()) && GoodsMarketEnum.UPPER.name().equals(goods.getMarketEnable()) &&
                        sku != null && sku.getAuthFlag().equals(GoodsAuthEnum.PASS.name()) && GoodsMarketEnum.UPPER.name().equals(sku.getMarketEnable());
            }).toList();
            esGoodsIndices.setRecords(list);
        }
        return esGoodsIndices;
    }

    /**
     * 添加选品库
     *
     * @param ids 商品id
     * @return
     */
    public Boolean addStorage(List<Integer> ids) {
        String token = this.getToken();
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        HttpRequest httpRequest = HttpUtil.createPost(str + "/app/product/storage/addStorage").header("x-token", token).body(JSONObject.toJSONString(map));
        String body = httpRequest.execute().body();

        return true;
    }


    /**
     * 查询自己店铺的下架数量
     * 供应商 toB   商家端 toC
     *
     * @return
     */
    @Override
    public ResultMessage<Object> getDownCount(String scene) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<Goods>();
        queryWrapper.eq(Goods::getDeleteFlag, Boolean.FALSE);
        queryWrapper.eq(Goods::getMarketEnable, "DOWN");
        //管理端
        queryWrapper.eq(Goods::getScene, scene);
        AuthUser currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            throw new ServiceException("无用户信息");
        }
        //商家端
        if (!SceneEnums.MANAGER.equals(currentUser.getScene()) && SceneEnums.STORE.name().equals(scene)) {
            queryWrapper.eq(Goods::getStoreId, currentUser.getExtendId());
        }
        //供应商
        if (!SceneEnums.MANAGER.equals(currentUser.getScene()) && SceneEnums.SUPPLIER.name().equals(scene)) {
            queryWrapper.eq(Goods::getStoreId, currentUser.getExtendId());
        }
        //管理端
        if (SceneEnums.MANAGER.equals(currentUser.getScene())) {
            queryWrapper.eq(Goods::getAuthFlag, "PASS");
        }
        return ResultUtil.data(super.count(queryWrapper));
    }


    /**
     * 每天晚上12点， 查看1688采集过来的数据，价格不对  或者库存小于 10（需要做成可配置）  就下架。
     */
    @SneakyThrows
    @Override
    public void isDown(String goodsId) {
        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsLambdaQueryWrapper.eq(Goods::getDeleteFlag, Boolean.FALSE);
        goodsLambdaQueryWrapper.eq(Goods::getMarketEnable, GoodsMarketEnum.UPPER.name());
        goodsLambdaQueryWrapper.like(Goods::getGoodsGrabUrl, "https://detail.1688.com");
//        if (StringUtils.isNotEmpty(goodsId)) {
            goodsLambdaQueryWrapper.in(Goods::getId, (Object[]) goodsId.split(","));
//        }
        List<Goods> goodsList = super.list(goodsLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(goodsList)) {
            LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(Goods::getSupplierGoodsId, goodsList.stream().map(Goods::getId).collect(Collectors.toList()));
            goodsList.addAll(super.list(lambdaQueryWrapper));
        }
        if (CollectionUtil.isEmpty(goodsList)) {
            log.info("未发现有需要比对价格的商品");
            return;
        }
        Setting setting = settingClient.get("STOCK");
        if (setting == null) {
            log.error("STOCK 配置为空");
            throw new ServiceException("STOCK 配置为空");
        }
        Map<String, SupplierGoodsOperationDTO> supplierMap = new HashMap<>();
        //缓慢采集商品价格,防止触发1688拦截
        for (Goods goods : goodsList) {
            try {
                Thread.sleep(3000);
                SupplierGoodsOperationDTO  supplierGoodsOperationDTO = goodsGrabService.getSupplierGoodsOperationDTO(goods.getGoodsGrabUrl());
                supplierMap.put(goods.getGoodsGrabUrl(), supplierGoodsOperationDTO);
            } catch (Exception e) {
                int times = 1;
                try {
                    do {
                        log.error("重试" + times + "次");
                        Thread.sleep(2000);
                        SupplierGoodsOperationDTO supplierGoodsOperationDTO = goodsGrabService.getSupplierGoodsOperationDTO(goods.getGoodsGrabUrl());
                        supplierMap.put(goods.getGoodsGrabUrl(), supplierGoodsOperationDTO);
                        times++;
                    } while (times <= 5);
                } catch (Exception exception) {
                    log.error("重试" + times + "次===== " + exception.getMessage());
                }
            }
        }

        for (Goods goods : goodsList) {
//            queue.put(goods);
//            SupplierGoodsOperationDTO  supplierGoodsOperationDTO = goodsGrabService.getSupplierGoodsOperationDTO(goods.getGoodsGrabUrl());
            SupplierGoodsOperationDTO supplierGoodsOperationDTO = supplierMap.get(goods.getGoodsGrabUrl());
            log.info("supplierGoodsOperationDTO ==== "+ JSONObject.toJSONString(supplierGoodsOperationDTO));
            //采集的skuList
            List<GoodsSku> skuList = new ArrayList<>();
            //为空直接下架，因为可能1688平台也下架了。
            if (supplierGoodsOperationDTO == null) {
                down(goods.getId());
                continue;
            }
            if (CollectionUtil.isNotEmpty(supplierGoodsOperationDTO.getSkuList())) {
                for (Map<String, Object> map : supplierGoodsOperationDTO.getSkuList()) {
                    GoodsSku sku = GoodsSkuBuilder.build(goods, map);
                    skuList.add(sku);
                }
            }
            //商品库的sku
            LambdaQueryWrapper<GoodsSku> goodsSkuLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsSkuLambdaQueryWrapper.eq(GoodsSku::getGoodsId, goods.getId());
            goodsSkuLambdaQueryWrapper.eq(GoodsSku::getDeleteFlag, Boolean.FALSE);
            List<GoodsSku> goodsSkus = goodsSkuService.list(goodsSkuLambdaQueryWrapper);

            //库存数量是否，小于配置数
            boolean isQuantity = true;
            List<Integer> quantityList = skuList.stream().map(GoodsSku::getQuantity).collect(Collectors.toList());
            for (Integer quantity : quantityList) {
                if (quantity < Integer.parseInt(setting.getSettingValue())) {
                    isQuantity = false;
                }
            }
            //两个集合的商品名 与成本价 与 价格是否有存在不一致的情况
            List<GoodsSku> caijiSku = skuList.stream().map(e -> new GoodsSku(e.getCost())).collect(Collectors.toList());
            List<GoodsSku> databaseSku = goodsSkus.stream().map(e -> new GoodsSku(e.getCost())).collect(Collectors.toList());
            caijiSku.sort(Comparator.comparing(GoodsSku::hashCode));
            databaseSku.sort(Comparator.comparing(GoodsSku::hashCode));
            boolean isFalse = caijiSku.toString().equals(databaseSku.toString());
            log.info("isFalse ==== {},  goods  == {}" , isFalse  , goods.getId());
            //两个集合的商品名 与成本价 与 价格有存在不一致的情况  ||  或者库存数量小于配置数   把我们平台的商品下架
            if (!isFalse || !isQuantity) {
                down(goods.getId());
            }
        }
        //return ResultUtil.success();
    }


    private void down(String goodsId) {
        LambdaUpdateWrapper<Goods> goodsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        goodsLambdaUpdateWrapper.eq(Goods::getId, goodsId);
        goodsLambdaUpdateWrapper.set(Goods::getMarketEnable, GoodsMarketEnum.DOWN);
        goodsLambdaUpdateWrapper.set(Goods::getAuthFlag, GoodsAuthEnum.TOBEAUDITED);
        super.update(goodsLambdaUpdateWrapper);
        this.clearCache(goodsId);
        // 发送删除es商品的信息
        applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent.builder().source("商品删除").exchange(amqpExchangeProperties.getGoods()).routingKey(GoodsRoutingKey.GOODS_DELETE).message(goodsId).build());

        LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        goodsSkuLambdaUpdateWrapper.eq(GoodsSku::getGoodsId, goodsId);
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getMarketEnable, GoodsMarketEnum.DOWN);
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getAuthFlag, GoodsAuthEnum.TOBEAUDITED);
        goodsSkuService.update(goodsSkuLambdaUpdateWrapper);

        LambdaQueryWrapper<GoodsSku> goodsSkuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsSkuLambdaQueryWrapper.eq(GoodsSku::getGoodsId, goodsId);
        goodsSkuLambdaQueryWrapper.eq(GoodsSku::getDeleteFlag, Boolean.FALSE);
        List<GoodsSku> goodsSkus = goodsSkuService.list(goodsSkuLambdaQueryWrapper);
        for (GoodsSku goodsSku : goodsSkus) {
            goodsSkuService.clearCache(goodsSku.getId());
            // 发送删除es商品的信息
            applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent.builder().source("商品SKU删除").exchange(amqpExchangeProperties.getGoods()).routingKey(GoodsRoutingKey.SKU_DELETE).message(goodsSku.getId()).build());
        }
    }

    /**
     * 清空指定店铺的商品缓存
     * @param storeId 店铺id
     * @return 是否成功
     */
    @Override
    public ResultMessage<Object> clearCacheByStoreId(String storeId) {
        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsLambdaQueryWrapper.eq(Goods::getStoreId, storeId);
        goodsLambdaQueryWrapper.eq(Goods::getMarketEnable, GoodsMarketEnum.UPPER.name());
        goodsLambdaQueryWrapper.eq(Goods::getDeleteFlag, Boolean.FALSE);
        goodsLambdaQueryWrapper.select(Goods::getId);
        List<Goods> goodsList = super.list(goodsLambdaQueryWrapper);
        for (Goods goods : goodsList) {
            this.clearCache(goods.getId());
        }

        LambdaQueryWrapper<GoodsSku> goodsSkuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsSkuLambdaQueryWrapper.in(GoodsSku::getGoodsId, goodsList.stream().map(Goods::getId).collect(Collectors.toList()));
        goodsSkuLambdaQueryWrapper.select(GoodsSku::getId);
        List<GoodsSku> goodsSkus = goodsSkuService.list(goodsSkuLambdaQueryWrapper);
        for (GoodsSku skus : goodsSkus) {
            goodsSkuService.clearCache(skus.getId());
        }
        return ResultUtil.success();
    }

    public void syncGoods() {
        Integer maxId = baseMapper.selectMaxId();
        GoodsSearchParams goodsSearchParams = new GoodsSearchParams();
        goodsSearchParams.setCursor(maxId);
        goodsSearchParams.setPageSize(100);
        Boolean addedGoods = addGoods(goodsSearchParams);
//        if (addedGoods) {
//            syncGoods();
//        }
        //同步goods的默认绿色积分与最低价格
        this.sycn();
    }
    /**
     * 店铺，批量添加分类
     *
     * 如果已存在该分类替换掉，然后在批量追加 。 普通商品
     * @param ids 商品id
     * @param categoryPathSon 分类id
     * @param categoryPathSonName 分类名称
     */
    @Override
    public void updateCategoryById(String ids, String categoryPathSon, String categoryPathSonName) {
        baseMapper.replaceCategoryById(Arrays.stream(ids.split(",")).collect(Collectors.toList()), "'"+categoryPathSon+"'", "'"+categoryPathSonName+"'");
        baseMapper.updateCategoryById(Arrays.stream(ids.split(",")).collect(Collectors.toList()), "'"+categoryPathSon+"'", "'"+categoryPathSonName+"'");
    }

    /**
     * 供应商，批量添加分类
     * 如果已存在该分类替换掉，然后在批量追加 。 代理商品
     * @param ids 商品id
     * @param categoryPathSon 分类id
     * @param categoryPathSonName 分类名称
     */
    @Override
    public void updateCategoryByIdOrSupplierId(String ids, String categoryPathSon, String categoryPathSonName) {
        baseMapper.replaceCategoryByIdOrSupplierId(Arrays.stream(ids.split(",")).collect(Collectors.toList()), "'"+categoryPathSon+"'","'"+categoryPathSonName+"'");
        baseMapper.updateCategoryByIdOrSupplierId(Arrays.stream(ids.split(",")).collect(Collectors.toList()), "'"+categoryPathSon+"'", "'"+categoryPathSonName+"'");
    }

    /**
     * 下单前校验能否下单
     * @param beforeCheckVO 下单信息，与地址
     * @return 能否下单(有运费即可下单)
     */
    public BeforeCheckRes beforeCheck(BeforeCheckVO beforeCheckVO) {
        Map<String, Object> params = new HashMap<>();

        Map<String, Object> addressMap = new HashMap<>();
        Map<String, Object> spu = new HashMap<>();
        addressMap.put("area", beforeCheckVO.getArea());
        addressMap.put("city", beforeCheckVO.getCity());
        addressMap.put("consignee", beforeCheckVO.getConsignee());
        addressMap.put("description", beforeCheckVO.getDescription());
        addressMap.put("phone", beforeCheckVO.getPhone());
        addressMap.put("province", beforeCheckVO.getProvince());
        addressMap.put("street", beforeCheckVO.getStreet());
        params.put("address", addressMap);

        spu.put("spu", beforeCheckVO.getSpuVOList());
        params.put("spu", spu);

        String token = getToken();
        HttpRequest httpRequest = HttpUtil.createPost(str + "/app/order/beforeCheck").header("x-token", token).body(JSONObject.toJSONString(params));
        String body = httpRequest.execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.getInteger("code") != 0) {
            throw new ServiceException("获取订单验证异常");
        }
        BeforeCheckRes beforeCheckRes = (BeforeCheckRes) jsonObject.get("data");
        return beforeCheckRes;
    }

    public DataVO appOrder(List<SpuVO> spuVOList,BeforeCheckVO beforeCheckVO, String orderSn, String remark) {
        Map<String, Object> params = new HashMap<>();
        params.put("spu", spuVOList);

        Map<String, Object> addressMap = new HashMap<>();
        addressMap.put("area", beforeCheckVO.getArea());
        addressMap.put("city", beforeCheckVO.getCity());
        addressMap.put("consignee", beforeCheckVO.getConsignee());
        addressMap.put("description", beforeCheckVO.getDescription());
        addressMap.put("phone", beforeCheckVO.getPhone());
        addressMap.put("province", beforeCheckVO.getProvince());
        addressMap.put("street", beforeCheckVO.getStreet());
        params.put("address", addressMap);
        params.put("order_sn", orderSn);
        params.put("remark", remark);

        String token = getToken();
        HttpRequest httpRequest = HttpUtil.createPost(str + "/app/order").header("x-token", token).body(JSONObject.toJSONString(params));
        String body = httpRequest.execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.getInteger("code") != 0) {
            throw new ServiceException("生成订单异常");
        }
        DataVO dataVO = (DataVO) jsonObject.get("data");
        return dataVO;
    }


    /**
     * 更新第三方平台id，到数据库
     */
    @Override
    public void updateThirdPartyPlatformId() {
        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsLambdaQueryWrapper.eq(Goods::getStoreId, "1713890839052210178");
        goodsLambdaQueryWrapper.eq(Goods::getCreateBy, "SYSTEM");
        goodsLambdaQueryWrapper.eq(Goods::getDeleteFlag, 0);
//        goodsLambdaQueryWrapper.eq(Goods::getMarketEnable, GoodsMarketEnum.UPPER.name());
//        goodsLambdaQueryWrapper.isNull(Goods::getThirdPartyPlatformId);
        goodsLambdaQueryWrapper.eq(Goods::getThirdPartyPlatformType, 1);
        goodsLambdaQueryWrapper.select(Goods::getId, Goods::getGoodsName);
        List<Goods> goodsList = super.list(goodsLambdaQueryWrapper);
        if (CollectionUtil.isEmpty(goodsList)) {
            return;
        }
        log.info("goodsList == {}", JSONObject.toJSONString(goodsList));
        goodsList.parallelStream().forEach(goods -> {
            log.info("goods == {}", JSONObject.toJSONString(goods));
            GoodsSearchParams goodsSearchParams = new GoodsSearchParams();
            goodsSearchParams.setPageSize(1);
            goodsSearchParams.setPageNumber(1);
            goodsSearchParams.setGoodsName(goods.getGoodsName().substring(2, goods.getGoodsName().length()));
            List<JSONObject> platformGoodsList = getPlatformGoodsList2(goodsSearchParams);
            log.info("platformGoodsList = {}", JSONObject.toJSONString(platformGoodsList));
            List<Goods> conversionList = goodsConversion(platformGoodsList);
            log.info("conversionList = {}", JSONObject.toJSONString(conversionList));
            conversionList.parallelStream().forEach(goods1 -> {
                log.info("goods1 = {}", JSONObject.toJSONString(goods1));
                LambdaUpdateWrapper<Goods> goodsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                goodsLambdaUpdateWrapper.eq(Goods::getStoreId, "1713890839052210178");
                goodsLambdaUpdateWrapper.eq(Goods::getCreateBy, "SYSTEM");
                goodsLambdaUpdateWrapper.eq(Goods::getGoodsName, goods.getGoodsName());
                goodsLambdaUpdateWrapper.set(Goods::getThirdPartyPlatformId, goods1.getThirdPartyPlatformId());
                goodsLambdaUpdateWrapper.set(Goods::getThirdPartyPlatformType, 1);
                baseMapper.update(null, goodsLambdaUpdateWrapper);
                System.out.println("22222 = " + 22222);
            });

            List<Integer> goodsIdList = conversionList.stream().map(Goods::getGid).collect(Collectors.toList());
            List<JSONObject> platformGoodsDetail = getPlatformGoodsDetail(goodsIdList);
            Map<String, List> map = goodsSkusConversion(platformGoodsDetail, conversionList);
            List goodsSku1 = map.get("goods_sku");
            if (CollectionUtil.isNotEmpty(goodsSku1)) {
                List<GoodsSku> goodsSku = (List<GoodsSku>) goodsSku1;
                goodsSku.parallelStream().forEach(sku -> {
                    LambdaUpdateWrapper<GoodsSku> skuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    skuLambdaUpdateWrapper.eq(GoodsSku::getStoreId, "1713890839052210178");
                    skuLambdaUpdateWrapper.eq(GoodsSku::getCreateBy, "SYSTEM");
                    skuLambdaUpdateWrapper.and( q-> q.eq(GoodsSku::getGoodsName, goods.getGoodsName() + " "+ sku.getSimpleSpecs()).or()
                            .eq(GoodsSku::getGoodsName, goods.getGoodsName()));
                    skuLambdaUpdateWrapper.set(GoodsSku::getThirdPartyPlatformType, 1);
                    skuLambdaUpdateWrapper.set(GoodsSku::getThirdPartyPlatformId, sku.getThirdPartyPlatformId());
                    goodsSkuService.update(skuLambdaUpdateWrapper);
                    System.out.println("33333 = " + 33333);
                });
            }
        });
    }

    /**
     * 清除goods缓存
     * @param goodsIds
     */
    @Override
    public void cleanGoodsCache (List<String> goodsIds) {
        List<String> cacheKeys = new ArrayList<>();
        goodsIds.forEach(i -> cacheKeys.add(CachePrefix.GOODS.getPrefix() + i));
        cache.multiDel(cacheKeys);
    }


    /**
     * 添加盲盒规则时，自动添加盲盒商品： 作用于前端APP购买。 商品类型BOX_GOODS
     *
     * @param boxMhgoodsVO 盲盒规则
     * @return 是否添加成功
     */
    @Override
    public boolean createGoods(BoxMhgoodsVO boxMhgoodsVO) {
        log.info("createGoods == {}", JSONObject.toJSONString(boxMhgoodsVO));
        Goods goods = new Goods();
        goods.setGoodsName(boxMhgoodsVO.getMhGoodsName());
        goods.setIntro(boxMhgoodsVO.getRemark());
        goods.setMobileIntro(boxMhgoodsVO.getRemark());
        goods.setOriginal(boxMhgoodsVO.getMhGoodsHomeImage());
        goods.setBig(boxMhgoodsVO.getMhGoodsHomeImage());
        goods.setSmall(boxMhgoodsVO.getMhGoodsHomeImage());
        goods.setThumbnail(boxMhgoodsVO.getMhGoodsHomeImage());
        goods.setPrice(boxMhgoodsVO.getMhGoodsPrice().doubleValue());
        goods.setGoodsType(GoodsTypeEnum.BOX_GOODS.name());
        goods.setMhId(boxMhgoodsVO.getId());

        this.commonGoods(goods);
        return true;
    }

    /**
     * 添加商品
     * @param goodsVO 商品
     * @return 是否成功
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public ResultMessage<Object> add(GoodsVO goodsVO) {
        log.info("add == {} ", JSONObject.toJSONString(goodsVO));
        Goods goods = new Goods();
        goods.setGoodsName(goodsVO.getGoodsName());
        goods.setOriginal(goodsVO.getGoodsImage());
        goods.setBig(goodsVO.getGoodsImage());
        goods.setSmall(goodsVO.getGoodsImage());
        goods.setThumbnail(goodsVO.getGoodsImage());
        goods.setPrice(goodsVO.getPrice());
        goods.setGoodsType(GoodsTypeEnum.BOX_PARENT_GOODS.name());
        goods.setPublishType(goodsVO.getPublishType() != null ? goodsVO.getPublishType() : DictConstant.PUBLISH_TYPE_00);
        goods.setMhId(goodsVO.getMhId());
        goods.setProbability(goodsVO.getProbability());
        goods.setGoodsTag(goodsVO.getGoodsTag());
        goods.setIntro(goodsVO.getIntro());

        this.commonGoods(goods);
        return ResultUtil.success();
    }

    /**
     * 删除统计数据
     * @param ids
     * @return
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public ResultMessage<Object> mhDelete(String ids) {
        log.info("mhDelete === {}" , ids);
        List<String> goodsIdList = Arrays.stream(ids.split(",")).toList();
        LambdaUpdateWrapper<Goods> goodsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        goodsLambdaUpdateWrapper.set(Goods::getMarketEnable, GoodsMarketEnum.DOWN.name());
        goodsLambdaUpdateWrapper.set(Goods::getDeleteFlag, Boolean.TRUE);
        goodsLambdaUpdateWrapper.in(Goods::getId, goodsIdList);
        super.update(goodsLambdaUpdateWrapper);

        LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getMarketEnable, GoodsMarketEnum.DOWN.name());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getDeleteFlag, Boolean.TRUE);
        goodsSkuLambdaUpdateWrapper.in(GoodsSku::getGoodsId, goodsIdList);
        goodsSkuService.update(goodsSkuLambdaUpdateWrapper);

        //将关联的盲盒也清除。
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Goods::getId, goodsIdList);
        queryWrapper.ne(Goods::getMhId, "");
        queryWrapper.isNotNull(Goods::getMhId);
        queryWrapper.select(Goods::getId, Goods::getMhId);
        List<Goods> goodsList = super.list(goodsLambdaUpdateWrapper);
        if (CollectionUtil.isNotEmpty(goodsList)) {
            for (Goods goods : goodsList) {
                boxMhGoodsClient.removeGoodsMh(goods.getMhId(), goods.getId());
            }
        }

        for (String goodsId : goodsIdList) {
            cache.remove(CachePrefix.GOODS.getPrefix() + goodsId);
            List<GoodsSku> goodsSkus = goodsSkuService.getGoodsSkuListByGoodsId(goodsId);
            if (CollectionUtil.isEmpty(goodsSkus)) {
                continue;
            }
            for (GoodsSku skus : goodsSkus) {
                cache.remove(CachePrefix.GOODS_SKU.getPrefix() + skus.getId());
            }
        }

        return ResultUtil.success();
    }

    /**
     * 修改盲盒数据
     *
     * @param goodsVO 盲盒数据
     * @return 是否成功
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public ResultMessage<Object> mhUpdate(GoodsVO goodsVO) {
        log.info("mhUpdate == {}" , JSONObject.toJSONString(goodsVO));
        Long count = boxMhGoodsClient.getBiZhongGoodsById(goodsVO.getId());
        //已经是大奖商品（大奖商品不允许有归属盲盒，防止被抽中），并且准备修改盲盒归属
        if (count > 0 && StringUtils.isNotEmpty(goodsVO.getMhId())) {
            throw new ServiceException("大奖商品不允许有归属盲盒，防止被抽中");
        }
        Goods goods = super.getById(goodsVO.getId());
        //如果是已发布，并且是进行中的盲盒 ： 概率不为空的标签下必须要有商品
        Boolean tagBol = goodsVO.getGoodsTag() != null && !goodsVO.getGoodsTag().equals(goods.getGoodsTag());
        Boolean mhBol = StringUtils.isNotEmpty(goodsVO.getMhId()) && (!goodsVO.getMhId().equals(goods.getMhId()));
        if (StringUtils.isNotEmpty(goods.getMhId()) && (tagBol || mhBol)) {
            BoxMhgoods boxMhgoodsVO = boxMhGoodsClient.getById(goods.getMhId());
            //是已发布，并且是进行中的盲盒
            if (boxMhgoodsVO != null && DictConstant.MH_STATUS_02.equals(boxMhgoodsVO.getMhStatus()) && DictConstant.PUBLISH_TYPE_01.equals(boxMhgoodsVO.getPublishType())) {
                List<BoxMhgoodsTag> mhgoodsTagList = boxMhGoodsClient.getTagListById(goods.getMhId());
                for (BoxMhgoodsTag mhgoodsTag : mhgoodsTagList) {
                    if (mhgoodsTag.getProbability() != null && mhgoodsTag.getProbability().doubleValue() != 0D) {
                        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        goodsLambdaQueryWrapper.eq(Goods::getMhId, goods.getMhId());
                        goodsLambdaQueryWrapper.eq(Goods::getGoodsTag, mhgoodsTag.getTag());
                        //修改了标签或者归属，就要把这条数据排掉
                        goodsLambdaQueryWrapper.ne(Goods::getId, goods.getId());
                        long count1 = super.count(goodsLambdaQueryWrapper);
                        if (count1 < 1) {
                            Dictionary dictionary = dictionaryClient.getDict(Dictionary.builder().code(DictConstant.TAG_NAME).status(DictConstant.STATUS_1).value(String.valueOf(mhgoodsTag.getTag())).build());
                            String valueName = dictionary != null ? dictionary.getValueName() : "";
                            throw new ServiceException("当前盲盒:"+boxMhgoodsVO.getMhGoodsName() + ",修改后" + valueName + "将没有商品");
                        }
                    }
                }
            }
        }

        LambdaUpdateWrapper<Goods> goodsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        goodsLambdaUpdateWrapper.set(Goods::getGoodsName, goodsVO.getGoodsName());
        goodsLambdaUpdateWrapper.set(Goods::getThumbnail, goodsVO.getGoodsImage());
        goodsLambdaUpdateWrapper.set(Goods::getOriginal, goodsVO.getGoodsImage());
        goodsLambdaUpdateWrapper.set(Goods::getBig, goodsVO.getGoodsImage());
        goodsLambdaUpdateWrapper.set(Goods::getSmall, goodsVO.getGoodsImage());
        goodsLambdaUpdateWrapper.set(Goods::getPrice, goodsVO.getPrice());
        goodsLambdaUpdateWrapper.set(Goods::getMhId, goodsVO.getMhId());
        goodsLambdaUpdateWrapper.set(Goods::getProbability, goodsVO.getProbability());
        goodsLambdaUpdateWrapper.set(Goods::getGoodsTag, goodsVO.getGoodsTag());
        goodsLambdaUpdateWrapper.set(Goods::getMobileIntro, goodsVO.getIntro());
        goodsLambdaUpdateWrapper.set(Goods::getIntro, goodsVO.getIntro());
        goodsLambdaUpdateWrapper.eq(Goods::getId, goodsVO.getId());
        super.update(goodsLambdaUpdateWrapper);

        LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getGoodsName, goodsVO.getGoodsName());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getThumbnail, goodsVO.getGoodsImage());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getOriginal, goodsVO.getGoodsImage());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getBig, goodsVO.getGoodsImage());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getSmall, goodsVO.getGoodsImage());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getPrice, goodsVO.getPrice());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getMhId, goodsVO.getMhId());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getMobileIntro, goodsVO.getIntro());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getIntro, goodsVO.getIntro());
        goodsSkuLambdaUpdateWrapper.eq(GoodsSku::getGoodsId, goodsVO.getId());
        goodsSkuService.update(goodsSkuLambdaUpdateWrapper);

        cache.remove(CachePrefix.GOODS.getPrefix() + goodsVO.getId());
        List<GoodsSku> goodsSkus = goodsSkuService.getGoodsSkuListByGoodsId(goodsVO.getId());
        if (CollectionUtil.isNotEmpty(goodsSkus)) {
            for (GoodsSku skus : goodsSkus) {
                cache.remove(CachePrefix.GOODS_SKU.getPrefix() + skus.getId());
            }
        }

        return ResultUtil.success();
    }

    /**
     * 发布状态变更
     * @param publishType 发布类型：1发布，2撤销发布
     * @param id 主键
     * @return 是否成功
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public ResultMessage<Object> mhPublish(Integer publishType, String id) {
        Goods goods = super.getById(id);
        if (goods == null || StringUtils.isEmpty(goods.getId())) {
            log.error("未获取到商品信息 == {}", id);
            throw new ServiceException("未获取到商品信息");
        }
        goods.setPublishType(publishType);
        if (DictConstant.PUBLISH_TYPE_01.equals(publishType)) {
            goods.setMarketEnable(GoodsMarketEnum.UPPER.name());
            goods.setAuthFlag(GoodsAuthEnum.PASS.name());
        }
        if (DictConstant.PUBLISH_TYPE_02.equals(publishType)) {
            goods.setMarketEnable(GoodsMarketEnum.DOWN.name());
            goods.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
        }
        super.updateById(goods);

        LambdaUpdateWrapper<GoodsSku> goodsSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        goodsSkuLambdaUpdateWrapper.eq(GoodsSku::getGoodsId, goods.getId());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getMarketEnable, goods.getMarketEnable());
        goodsSkuLambdaUpdateWrapper.set(GoodsSku::getAuthFlag, goods.getAuthFlag());
        goodsSkuService.update(goodsSkuLambdaUpdateWrapper);

        cache.remove(CachePrefix.GOODS.getPrefix() + id);
        List<GoodsSku> goodsSkus = goodsSkuService.getGoodsSkuListByGoodsId(id);
        if (CollectionUtil.isNotEmpty(goodsSkus)) {
            for (GoodsSku skus : goodsSkus) {
                cache.remove(CachePrefix.GOODS_SKU.getPrefix() + skus.getId());
            }
        }
        return ResultUtil.success();
    }

    private void commonGoods(Goods goods) {
        goods.setGoodsUnit("件");
        goods.setGrade(100D);
        goods.setBuyCount(0);
        goods.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
        goods.setMarketEnable(GoodsMarketEnum.DOWN.name());
        goods.setQuantity(100000);
        goods.setRecommend(true);
        goods.setSalesModel("RETAIL");
        goods.setSelfOperated(true);
        goods.setTemplateId("0");
        goods.setIsGreenGoods(false);
        goods.setIsVipGoods(false);
        goods.setScene(Objects.requireNonNull(UserContext.getCurrentUser()).getScene().name());
        goods.setExtendId(Objects.requireNonNull(UserContext.getCurrentUser()).getExtendId());
        goods.setStoreId(Objects.requireNonNull(UserContext.getCurrentUser()).getExtendId());
        goods.setStoreName(Objects.requireNonNull(UserContext.getCurrentUser()).getExtendName());
        goods.setPublishType(DictConstant.PUBLISH_TYPE_00);
        goods.setMobileIntro(goods.getIntro());
        goods.setParams("[]");
        goods.setCategoryPath("-1,-1,-1");

        boolean save = super.save(goods);
        GoodsSku goodsSku = new GoodsSku();
        goodsSku.setBuyCount(0);
        goodsSku.setCommentNum(0);
        goodsSku.setGoodsId(goods.getId());
        goodsSku.setGoodsName(goods.getGoodsName());
        goodsSku.setStoreId(goods.getStoreId());
        goodsSku.setStoreName(goods.getStoreName());
        String img = StringUtils.isNotEmpty(goods.getThumbnail()) ? goods.getThumbnail() : null;
        String specs = "{\"images\":[{\"url\":\"" + img + "\"}]" + "," + "\"" + "默认" + "\"" + ":" + "\"" + "默认" + "\"";
        goodsSku.setSpecs(specs + "}");
        goodsSku.setSimpleSpecs("默认");
        goodsSku.setGoodsType(goods.getGoodsType());
        goodsSku.setIsGreenGoods(false);
        goodsSku.setQuantity(goods.getQuantity());
        goodsSku.setWeight(null);
        goodsSku.setCost(goods.getPrice());
        goodsSku.setPrice(goods.getPrice());
        goodsSku.setScene(Objects.requireNonNull(UserContext.getCurrentUser()).getScene().name());
        goodsSku.setFreightTemplateId("0");
        goodsSku.setGrade(100D);
        goodsSku.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
        goodsSku.setMarketEnable(GoodsMarketEnum.DOWN.name());
        goodsSku.setRecommend(true);
        goodsSku.setSalesModel(goods.getSalesModel());
        goodsSku.setSelfOperated(true);
        goodsSku.setTemplateId("0");
        goodsSku.setOriginal(img);
        goodsSku.setThumbnail(img);
        goodsSku.setBig(img);
        goodsSku.setSmall(img);
        goodsSku.setIsProxyGoods(false);
        goodsSku.setSupportProxy(false);
        goodsSku.setSupportPurchase(false);
        goodsSku.setExtendId(goods.getExtendId());
        goodsSku.setGoodsUnit("件");
        goodsSku.setIntro(goods.getIntro());
        goodsSku.setMobileIntro(goods.getMobileIntro());
        goodsSku.setMaxfNumber(0D);
        goodsSku.setMhId(goods.getMhId());
        goodsSku.setGoodsId(goods.getId());
        goodsSku.setCategoryPath(goods.getCategoryPath());
        boolean skuSave = goodsSkuService.save(goodsSku);
    }

    /**
     * 获取门票商品信息
     * @return
     */
    @Override
    public Goods getTicketGoods () {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getIsTicket, true);
        queryWrapper.eq(Goods::getAuthFlag, GoodsAuthEnum.PASS.name());
        queryWrapper.eq(Goods::getMarketEnable, GoodsMarketEnum.UPPER.name());
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    private LambdaQueryWrapper<Goods> initQuery(GoodsHotPopularDTO dto){
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        //非供应商商品
        queryWrapper.in(true, Goods::getScene, "MEMBER", "STORE", "MANAGER");
        //上架的商品
        queryWrapper.eq(true, Goods::getMarketEnable, GoodsMarketEnum.UPPER.name());
        queryWrapper.likeRight(StrUtil.isNotBlank(dto.getGoodsName()), Goods::getGoodsName, dto.getGoodsName());
        return queryWrapper;
    }

    @Override
    public Page<Goods> selectGoodsList(GoodsHotPopularDTO dto) {
        return baseMapper.selectGoodsListPaging(new Page<>(dto.getPageNumber(), dto.getPageSize()),dto);
    }


    /**
     * 活动选择商品
     * @param searchParams
     * @return
     */
    @Override
    public Page<Goods> getGoodsByPage(GoodsSearchParams searchParams) {
        QueryWrapper<Goods> queryWrapper = searchParams.queryWrapper();

        // 全返商品查询，过滤促销活动商品
        if (null != searchParams.getSceneType() && 0 == searchParams.getSceneType()) {
            PromotionGoodsSearchParams params = new PromotionGoodsSearchParams();
            params.setPromotionStatus(PromotionsStatusEnum.START.name() + "," + PromotionsStatusEnum.NEW.name());
            params.setStoreId(Objects.requireNonNull(UserContext.getCurrentUser()).getExtendId());
            List<PromotionGoods> promotionGoodsList = promotionGoodsClient.listFindAll(params);
            if (!promotionGoodsList.isEmpty()) {
                List<String> goodsList = promotionGoodsList.stream().map(PromotionGoods::getGoodsId).toList();
                if (!goodsList.isEmpty()) {
                    queryWrapper.notIn("id", goodsList);
                }
            }
        }else {
            // 过滤全返商品
            List<ReturnActivityGoods> returnActivityGoodsList = returnActivityGoodsClient.getListByStoreId(Objects.requireNonNull(UserContext.getCurrentUser()).getExtendId());
            if (!returnActivityGoodsList.isEmpty()) {
                List<String> goodsList = returnActivityGoodsList.stream().map(ReturnActivityGoods::getGoodsId).toList();
                queryWrapper.notIn("id", goodsList);
            }
        }
        SceneHelp.queryHandler(queryWrapper, true);
        Page<Goods> page = this.page(PageUtil.initPage(searchParams), queryWrapper);
        if (!page.getRecords().isEmpty()) {
            page.getRecords().forEach(goods -> {
                goods.setGoodsId(goods.getId());
            });
        }
        return page;
    }

    /**
     * 获取运营中心下的，供应商 --》 获取供应商的商品 --》统计数据
     * 首页商品数量统计
     */
    @Override
    public ResultMessage<HomeResult> commodityQuantityStatistics() {
        HomeResult homeResult = HomeResultUtil.createDefaultValue();
        //获取运营中心下的，供应商
        List<Store> storeList = storeClient.getStoreList();
        if (CollectionUtil.isEmpty(storeList)) {
            return ResultUtil.data(homeResult);
        }
        //获取供应商的商品
        List<String> storeIdList = storeList.stream().map(Store::getId).toList();
        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsLambdaQueryWrapper.in(Goods::getExtendId, storeIdList);
        List<Goods> goodsList = super.list(goodsLambdaQueryWrapper);
        log.info("goodsList === {}", JSONObject.toJSONString(goodsList));
        if (CollectionUtil.isEmpty(goodsList)) {
            return ResultUtil.data(homeResult);
        }
        //计算返回值
        homeResult = HomeResultUtil.createResult(goodsList, goods -> {
            Date createDate = goods.getCreateTime();
            return createDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        });
        //获取本月违规下架
        YearMonth currentMonth = YearMonth.now();
        LocalDate firstDayOfMonth = currentMonth.atDay(1);
        LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();
        LambdaQueryWrapper<GoodsDownRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(GoodsDownRecord::getGoodsId, goodsList.stream().map(Goods::getId).collect(Collectors.toList()));
        queryWrapper.between(GoodsDownRecord::getCreateTime, firstDayOfMonth, lastDayOfMonth);
        homeResult.setViolationThisMonthCount(goodsDownRecordService.count(queryWrapper));
        return ResultUtil.data(homeResult);
    }

    /**
     * 根据供应商id集合获取商品数量
     * @param storeIds
     * @return
     */
    @Override
    public long getGoodsCountByStoreIds (List<String> storeIds, String marketEnable) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Goods::getExtendId, storeIds);
        queryWrapper.eq(Goods::getScene, SceneEnums.SUPPLIER.name());
        if (StringUtils.isNotEmpty(marketEnable)) {
            if (marketEnable.equals(GoodsMarketEnum.UPPER.name())) {
                queryWrapper.eq(Goods::getMarketEnable, marketEnable);
            }else if (marketEnable.equals(GoodsMarketEnum.DOWN.name())) {
                queryWrapper.and(tmp -> tmp.isNotNull(Goods::getUnderMessage).or().ne(Goods::getUnderMessage, ""));
            }
        }
        queryWrapper.eq(Goods::getAuthFlag, GoodsAuthEnum.PASS.name());
        return this.count(queryWrapper);
    }

    /**
     * 根据供应商id集合获取本月商品数量
     * @param storeIds
     * @return
     */
    @Override
    public long getCurrentMonthGoodsCountByStoreIds (List<String> storeIds) {
        return this.baseMapper.getCurrentMonthGoodsCountByStoreIds(storeIds);
    }

    @Override
    public long getGoodsCountByParams (List<String> storeIds, Date startTime, Date endTime) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Goods::getExtendId, storeIds);
        queryWrapper.eq(Goods::getScene, SceneEnums.SUPPLIER.name());
        if (null != startTime && null != endTime) {
            queryWrapper.between(Goods::getCreateTime, startTime, endTime);
        }
        return this.count(queryWrapper);
    }


    /**
     * 运营中心-服务商-供货商家列表
     * @param
     * @return
     */
    @Override
    public Page<OperationCenterSupplierVo> getSupplierByPage(OperationCenterSupplierDTO dto) {
        //查营中心下的供应商：
        //lilishop_urban_substation.li_urban_substation  城市站点表
        //运营中心账号下的城市分站 priviceId --->城市 分站id = li_stoer.urban_user_id
        //下架记录  li_goods_down_record  -->  supplier_id 供应商id
        AuthUser authUser = UserContext.getCurrentUser();
        if (null != authUser) {
            log.info("#getSupplierByPage# 运营中心-服务商-供货商家列表,获取当前登陆的账号信息:{}", JSONObject.toJSONString(authUser));
            OperationCenter operationCenter = operationCenterClient.getOperationCenter(authUser.getId());
            if (null == operationCenter) {
                throw new ServiceException("当前账号未找到运营中心相关信息");
            }
            log.info("#getSupplierByPage# 运营中心-服务商-供货商家列表,根据id查询到运营中心账号信息:{}", JSONObject.toJSONString(operationCenter));
            //LocalDateTime startOfMonth = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0);
            //dto.setStartTime(startOfMonth);
            //dto.setEndTime(dto.getStartTime().plusMonths(1));
            dto.setProvinceId(operationCenter.getProvinceId());

            LocalDateTime startOfMonth = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
            LocalDateTime endOfMonth = LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
            dto.setStartTime(Date.from(startOfMonth.atZone(ZoneId.systemDefault()).toInstant()));
            dto.setEndTime(Date.from(endOfMonth.atZone(ZoneId.systemDefault()).toInstant()));
            Page<OperationCenterSupplierVo> page = baseMapper.getSupplierByPage(new Page<>(dto.getPageNumber(), dto.getPageSize()), dto);
            return page;
        } else {
            throw new ServiceException("未登陆");
        }
    }

    @Override
    public List<Order> sycnFreeOrder() {
        return baseMapper.sycnFreeOrder();
    }


    /**
     * 免税商品-获取前20条热销商品
     * @param params
     * @return
     */
    @Override
    public Page<GoodsVO> getHotSalesGoods(GoodsSearchParams params) {
        params.setPageNumber(1);
        params.setPageSize(20);
        //加架的商品
        params.setMarketEnable(GoodsMarketEnum.UPPER.name());
        //审核通过的商品
        params.setAuthFlag(GoodsAuthEnum.PASS.name());
        //查询热销商品排序  1,热销商品 2,新品商品
        params.setQueryType(1);
        Page<GoodsVO> page = baseMapper.getFreeTaxGoods(params, new Page<>(params.getPageNumber(), params.getPageSize(), false));
        return page;
    }

    /**
     * 免税商品-获取最新50条新上架商品
     * @param params
     * @return
     */
    @Override
    public Page<GoodsVO> getNewestGoods(GoodsSearchParams params) {
        params.setPageNumber(1);
        params.setPageSize(50);
        //加架的商品
        params.setMarketEnable(GoodsMarketEnum.UPPER.name());
        //审核通过的商品
        params.setAuthFlag(GoodsAuthEnum.PASS.name());
        //查询热销商品排序  1,热销商品 2,新品商品
        params.setQueryType(2);
        Page<GoodsVO> page = baseMapper.getFreeTaxGoods(params, new Page<>(params.getPageNumber(), params.getPageSize(), false));
        return page;
    }

    @Override
    public Long countSkuNumByGoods(String storeId) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Goods::getStoreId, storeId)
                .eq(Goods::getDeleteFlag, Boolean.FALSE)
                .eq(Goods::getAuthFlag, GoodsAuthEnum.PASS.name())
                .eq(Goods::getMarketEnable, GoodsMarketEnum.UPPER.name());
        return this.count(queryWrapper);
    }
}